package com.future.cb.common.utils;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class HttpUtil {
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 
	 * @param url
	 *            Url
	 * @param body
	 *            JsonBody
	 * @param uriVariables
	 *            url上可拼接的参数 如 a=1&b=2
	 * @return
	 */
	public String postJson(String url, Object body, Map<String, String> uriVariables) {
		try {
			if (uriVariables == null) {
				uriVariables = new HashMap<String, String>();
			}
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			ObjectMapper mapper = new ObjectMapper();
			String jsonObj = mapper.writeValueAsString(body);
			HttpEntity<String> httpEntity = new HttpEntity<String>(jsonObj, headers);
			return this.restTemplate.postForObject(url, httpEntity, String.class, uriVariables);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 
	 * @param url
	 * @param uriVariables url上可拼接的参数 如 a=1&b=2
	 * @return
	 */
	public String get(String url, Map<String, String> uriVariables) {
		if (uriVariables == null) {
			uriVariables = new HashMap<String, String>();
		}
		return this.restTemplate.getForObject(url, String.class, uriVariables);

	}
}
